import base64
import pickle

from django.shortcuts import render

# Create your views here.
from django import http
from django.views import View
import json

from django_redis import get_redis_connection

from carts.contants import CARTS_COOKIE_EXPIRES
from goods.models import SKU
from meiduo_mall.utils.response_code import RETCODE


class CartsView(View):
    def get(self, request):
        user = request.user
        if user.is_authenticated:
            redis_conn = get_redis_connection('carts')

            redis_carts = redis_conn.hgetall('carts_%s' % user.id)
            carts_selected = redis_conn.smembers('selected_%s' % user.id)

            carts_dict = {}
            for sku_id, count in redis_carts.items():
                carts_dict[int(sku_id)] = {  # redis中的数据是字节类型的
                    'count': int(count),
                    'selected': sku_id in carts_selected
                }

        else:
            carts_str = request.COOKIES.get('carts')
            if carts_str:
                carts_dict = pickle.loads(base64.b64decode(carts_str.encode()))
            else:
                carts_dict = {}
        print(carts_dict)
        sku_ids = carts_dict.keys()
        print(sku_ids)
        skus = SKU.objects.filter(id__in=sku_ids)
        carts_skus = []
        for sku in skus:
            carts_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': carts_dict.get(sku.id).get('count'),
                'selected': str(carts_dict.get(sku.id).get('selected')),
                'default_image_url': sku.default_image.url,
                'price': str(sku.price),
                'amount': str(sku.price * carts_dict.get(sku.id).get('count'))
            })
        # sku_ids = carts_dict.keys()
        # skus = SKU.objects.filter(id__in=sku_ids)
        # cart_skus = []
        # for sku in skus:
        #     cart_skus.append({
        #         'id': sku.id,
        #         'name': sku.name,
        #         'count': carts_dict.get(sku.id).get('count'),
        #         'selected': str(carts_dict.get(sku.id).get('selected')),  # 将True，转'True'，方便json解析
        #         'default_image_url': sku.default_image.url,
        #         'price': str(sku.price),  # 从Decimal('10.2')中取出'10.2'，方便json解析
        #         'amount': str(sku.price * carts_dict.get(sku.id).get('count')),
        #     })

        context = {
            'carts_skus': carts_skus
        }
        return render(request, 'cart.html', context)

    def post(self, request):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)

        # 校验参数
        if not all([sku_id, count]):
            return http.HttpResponseForbidden('参数不完整')

        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden("为查询到sku_id")

        try:
            count = int(count)
        except Exception as e:
            return http.HttpResponseForbidden('count不为整数')

        if not isinstance(selected, bool):
            return http.HttpResponseForbidden('selected参数不正确')

        user = request.user

        if user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()

            pl.hincrby('carts_%s' % user.id, sku_id, count)

            if selected:
                pl.sadd('selected_%s' % user.id, sku_id)
            pl.execute()

            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})


        else:
            carts_str = request.COOKIES.get('carts')
            if carts_str:
                carts_dict = pickle.loads(base64.b64decode(carts_str.encode()))
            else:
                carts_dict = {}

        print(carts_dict, "1111111")
        if sku_id in carts_dict:
            origin_count = carts_dict[sku_id][count]
            count += origin_count
        print(sku_id)
        carts_dict[sku_id] = {
            'selected': selected,
            'count': count
        }

        cookie_carts_str = base64.b64encode(pickle.dumps(carts_dict)).decode()

        response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': "未登录用户添加购物车成功"})
        response.set_cookie('carts', cookie_carts_str, max_age=CARTS_COOKIE_EXPIRES)

        return response

    def put(self, request):
        """修改购物车"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)

        # 判断参数是否齐全
        if not all([sku_id, count]):
            return http.HttpResponseForbidden('缺少必传参数')
        # 判断sku_id是否存在
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('商品sku_id不存在')
        # 判断count是否为数字
        try:
            count = int(count)
        except Exception:
            return http.HttpResponseForbidden('参数count有误')
        # 判断selected是否为bool值
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('参数selected有误')

        # 判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # 用户已登录，修改redis购物车
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()
            # 因为接口设计为幂等的，直接覆盖
            pl.hset('carts_%s' % user.id, sku_id, count)
            # 是否选中
            if selected:
                pl.sadd('selected_%s' % user.id, sku_id)
            else:
                pl.srem('selected_%s' % user.id, sku_id)
            pl.execute()

            # 创建响应对象
            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price,
                'amount': sku.price * count,
            }
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '修改购物车成功', 'cart_sku': cart_sku})

        else:
            # 用户未登录，修改cookie购物车
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                # 将cart_str转成bytes,再将bytes转成base64的bytes,最后将bytes转字典
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}
            # 因为接口设计为幂等的，直接覆盖
            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }
            # 将字典转成bytes,再将bytes转成base64的bytes,最后将bytes转字符串
            cookie_cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()

            # 创建响应对象
            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price,
                'amount': sku.price * count,
            }
            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': '修改购物车成功', 'cart_sku': cart_sku})
            # 响应结果并将购物车数据写入到cookie
            response.set_cookie('carts', cookie_cart_str, max_age=CARTS_COOKIE_EXPIRES)
            return response

    def delete(self, request):
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')

        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseNotFound('商品不存在')

        user = request.user
        if user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()

            pl.hdel('carts_%s' % user.id, sku_id)
            pl.srem('selected_%s' % user.id, sku_id)
            pl.execute()

            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '删除购物车成功'})

        else:
            carts_str = request.COOKIES.get('carts')
            if carts_str:
                carts_dict = pickle.loads(base64.b64decode(carts_str.encode()))
            else:
                carts_dict = {}
            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': '删除购物车成功'})
            if sku_id in carts_dict:
                del carts_dict[sku_id]
                cookie_carts_str = base64.b64encode(pickle.dumps(carts_dict)).decode()
                response.set_cookie('carts', cookie_carts_str, max_age=CARTS_COOKIE_EXPIRES)
            return response


class CartsSelectAll(View):
    def put(self, request):
        json_dict = json.loads(request.body.decode())
        selected = json_dict.get('selected', True)

        if not isinstance(selected, bool):
            return http.HttpResponseForbidden('参数格式不正确')

        user = request.user

        if user.is_authenticated:
            redis_conn = get_redis_connection('carts')

            skus = redis_conn.hgetall('carts_%s' % user.id)
            sku_ids = skus.keys()
            if selected:
                for sku_id in sku_ids:
                    redis_conn.sadd('selected_%s' % user.id, sku_id)
            else:
                redis_conn.srem('selected_%s' % user.id, *sku_ids)

            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '全选购物车成功'})

        else:
            skus = request.COOKIES.get('carts')
            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': '全选购物车成功'})
            if skus is not None:
                skus_dict = pickle.loads(base64.b64decode(skus.encode()))
                for sku_id in skus_dict:
                    skus_dict[sku_id]['selected'] = 'True'
                cookie_skus_dict = base64.b64encode(pickle.dumps(skus_dict)).decode()
                response.set_cookie('carts', cookie_skus_dict, max_age=CARTS_COOKIE_EXPIRES)
            return response
